package com.example.demo11.util;

import java.sql.*;

public class JDBC_Demo {
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("加载驱动失败"+ e.getMessage());
            throw new ExceptionInInitializerError(e);
        }
    }
    public static void main(String[] args) {
        Connection conn=null;
        Statement stmt=null;
        ResultSet rs=null;
        try {
            String url="jdbc:mysql://localhost:3306/dxm";
            String user="root";
            String password="123456";
            conn= DriverManager.getConnection(url,user,password);
            System.out.println("连接成功");
            stmt=conn.createStatement();
            String sql="select * from students";
            rs=stmt.executeQuery(sql);

            while (rs.next()){
                int id=rs.getInt("students_id");
                String name=rs.getString("students_name");
                System.out.println(id+" "+name);

            }

        }catch (SQLException e){
            System.out.println("连接失败"+e.getMessage());
            e.printStackTrace();


        }finally {
            try {
                if (rs!=null){
                    rs.close();
                }
                if (stmt!=null){
                    stmt.close();
                }
                if (conn!=null){
                    conn.close();
                }
            }catch (SQLException e){
                System.out.println("关闭失败"+e.getMessage());
                e.printStackTrace();
            }
        }

    }

}
